package com.kangtu.demointerceptortest.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @program: demo-weix-pay
 * @description: MyInterceptor
 * @author: 亮子说编程
 * @create: 2021-03-05 17:36
 **/
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("uri=" + request.getRequestURI());
        System.out.println("user=" + request.getRemoteUser());
        System.out.println("url=" + request.getRequestURL());
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String token = request.getHeader("token");
        System.out.println("token="+token);
        if (token != null) {
            return true;
        }

        System.out.println(username +","+password);

        if("xiongda".equals(username) && "123456".equals(password)) {
            return true;
        }else {
            //-- 结构化返回结果
            response.setStatus(403);
            response.setHeader("Content-Type", "application/json;charset=utf-8");

            HashMap<String, Object> map = new HashMap<>();
            map.put("code", -1);
            ObjectMapper mapper = new ObjectMapper();
            String message = mapper.writeValueAsString(map);

            response.getWriter().print(message);
            response.getWriter().flush();
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("================= jin ru  after ===============");
    }

}
